var amapFile = require('../../libs/amap-wx.js');
var Config = require('../../libs/config.js');
var location = require('../../libs/location.js');
const util = require('../../utils/util')
const AUTH = require('../../utils/auth')

// 辅助函数，用于获取逆地理编码信息并设置marker数据
function getRegeoInfo(that, location, isDevice) {
  myAmapFun.getRegeo({
    iconPath: "../../images/marker.png",
    iconWidth: 20,
    iconHeight: 30,
    location: location,
    success: function (data) {
      const marker = {
        id: 0,
        latitude: data[0].latitude,
        longitude: data[0].longitude,
        iconPath: data[0].iconPath,
        width: data[0].width,
        height: data[0].height
      };
      const textDataKey = isDevice ? 'deviceTextData' : 'phoneTextData';

      // 更新设备地址的markers数组
      if (isDevice) {
        that.setData({
          markers: [marker]
        });
      }
      // 设置地址描述信息
      that.setData({
        [textDataKey]: {
          name: data[0].name,
          desc: data[0].desc
        },
      });
      // 设置中心点的经纬度
      // if (that.data.currentView == 'device') {
      //   that.setData({
      //     latitude: that.data.deviceLatitude,
      //     longitude: that.data.deviceLongitude
      //   });
      // } else {
      //   that.setData({
      //     latitude: that.data.phoneLatitude,
      //     longitude: that.data.phoneLongitude
      //   });
      // }
    },
    fail: function (info) {
      console.error('获取逆地理编码信息失败:', info);
    }
  });
}

async function getWebLocationAndInfo(that) {
  //1.从web上获取定位器经纬度地址
  const res = await location.getLocationByToken();
  if (res.code == 200) {
    //先写死，后续从web获取 longitude,latitude,
    var spot = res.data.data.lng + "," + res.data.data.lat;
    //  c = "118.5977" + ",39.2068"
    console.log("getWebLocation值:" + spot);
    wx.setStorage({
      key: "deviceLocation",
      data: spot
    });
    that.setData({
      deviceLatitude: res.data.data.lat,
      deviceLongitude: res.data.data.lng,
      locationTime: res.data.data.locationTime
    });
    //2.获取该经纬度的地址信息（先执行获取定位器的经纬度之后才能执行这个）
    getRegeoInfo(that, spot, true);
    // 
  } else {
    console.log("定位器位置调用失败");
    // var l = [{
    //   longitude: "118.5977",
    //   latitude: "39.2068",
    //   id: 0
    // }]
  }
}

function getWxLocationAndInfo(that) {
  //获取本机wx地址，通过经纬度解析成具体位置，在地图上显示图像
  wx.getLocation({
    type: 'gcj02',
    success: function (res) {
      // 首次进入小程序先把中心点设置成微信的位置
      if (that.data.firstIn) {
        that.setData({
          firstIn: false,
          latitude: res.latitude,
          longitude: res.longitude,
        });
      }
      that.setData({
        phoneLatitude: res.latitude,
        phoneLongitude: res.longitude,
      });
      // console.log("获取到wx地址:" + res.longitude + "," + res.latitude)
      getRegeoInfo(that, res.longitude + "," + res.latitude, false);
    },
  })
}
async function getWebAndWxLocationAndInfo(that) {
  await getWebLocationAndInfo(that)
  getWxLocationAndInfo(that)
}
//定义为全局变量,高德地图的配置
var key = Config.Config.key;
var myAmapFun;

Page({
  data: {
    markers: [],
    latitude: '', //中心点纬度
    longitude: '', //中心点经度
    phoneLatitude: '', //手机纬度
    phoneLongitude: '', //手机经度
    deviceLatitude: '', //设备纬度
    deviceLongitude: '', //设备经度
    locationTime: '',
    deviceTextData: {}, //定位器的位置信息
    phoneTextData: {}, //手机的地址信息
    currentView: 'phone',
    firstIn: true,
  },
  onLoad: function () {
    //高德地图API的设置
    myAmapFun = new amapFile.AMapWX({
      key: key
    });
  },
  //页面展示时进行权限校验
  onShow: function () {
    // 先用AUTH检查用户是否登录
    AUTH.checkHasLogined().then(isLogined => {
      // console.log("输出" + isLogined)
      if (isLogined) {
        var that = this
        getWebAndWxLocationAndInfo(that)

        //如果设置了地图的自动刷新
        if (Config.Config.refresh) {
          // 设置定时器
          that.timer = setInterval(function () {
            // console.log("开始计时")
            getWebAndWxLocationAndInfo(that)
          }, Config.Config.refreshTime)
        }
      } else {
       AUTH.authorize().then(res => {
          //先认证，然后重新加载页面
          console.log("Token无效，重新授权")
          this.onShow();
        })
      }
    })
  },
  // 在页面的 onHide 或者 onUnload 方法中清除定时器
  onUnload: function () {
    var that = this
    clearInterval(that.timer);
  },
  // 视角切换
  onChangeView() {
    var that = this
    //切换视角!!
    const mapCtx = wx.createMapContext('map', that);
    if (that.data.currentView == 'device') {
      //切换到当前位置
      mapCtx.moveToLocation({
        latitude: Number(that.data.phoneLatitude),
        longitude: Number(that.data.phoneLongitude),
        success: () => {
          that.setData({
            currentView: 'phone',
          });
        },
        fail: () => {
          that.setData({
            currentView: 'device',
          });
        }
      });
    } else {
      //切换到设备位置
      //参数，将字符串转成number类型
      var parm = {
        latitude: Number(that.data.deviceLatitude),
        longitude: Number(that.data.deviceLongitude),
        success: () => {
          that.setData({
            currentView: 'device',
          });
        },
        fail: () => {
          that.setData({
            currentView: 'phone',
          });
        }
      }
      mapCtx.moveToLocation(parm);
    }
  },
  //打开高德地图/腾旭地图
  onOpenMapApp() {
    const version = wx.getSystemInfoSync().SDKVersion

    if (util.compareVersion(version, '2.14.0') < 0) {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showToast({
        title: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        icon: 'none'
      })
      return;
    }
    const mapCtx = wx.createMapContext('map', this);
    mapCtx.openMapApp({
      longitude: Number(this.data.deviceLongitude),
      latitude: Number(this.data.deviceLatitude),
      destination: this.data.deviceTextData.desc
    })
  },
  onShareAppMessage() {},
})